package cn.hdustea.shopNavigation.ui.view

import android.content.Context
import android.content.Intent
import cn.hdustea.shopNavigation.R
import cn.hdustea.shopNavigation.config.ConfigKey
import cn.hdustea.shopNavigation.entity.UserEntity
import cn.hdustea.shopNavigation.ui.contract.AccountContract
import cn.hdustea.shopNavigation.ui.presenter.AccountPresenter
import com.hdustea.base.base.BaseActivity
import com.hdustea.base.util.ToastUtil
import kotlinx.android.synthetic.main.activity_login.*

class AccountActivity : BaseActivity<AccountContract.Presenter>(), AccountContract.View {

    companion object {
        fun startActivity(context: Context) {
            val intent = Intent(context, AccountActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initView() {

        btn_login.setOnClickListener {
            if (!cb_protocol.isChecked) {
                showToast("您需要先同意服务协议才能登录")
                return@setOnClickListener
            }

            if (et_phone.text.toString().isEmpty()) {
                et_phone.error = "用户名不能为空"
                return@setOnClickListener
            } else {
                et_phone.error = null
            }

            when {
                et_code.text.toString().isEmpty() -> {
                    et_code.error = "密码不能为空"
                    return@setOnClickListener
                }
                et_code.text.toString().length < 4 -> {
                    et_code.error = "请至少输入4个字符"
                    return@setOnClickListener
                }
                else -> {
                    et_code.error = null
                }
            }
            showLoading()
            mPresenter?.login(et_phone.text.toString(), et_code.text.toString())
        }

    }

    override fun getLayoutRes(): Int = R.layout.activity_login

    override fun getPresenter(): AccountContract.Presenter = AccountPresenter(this)

    override fun loginSuccess(userEntity: UserEntity?) {
        if (userEntity == null) {
            ToastUtil.showShort("用户名或密码错误")
        } else {
            ConfigKey.setUserId(userEntity.id)
            ConfigKey.setUserName(userEntity.nickname)
            ConfigKey.setUserPhone(userEntity.phone)
            ConfigKey.setUserPortrait(userEntity.headImg)

            finish()
        }
    }

    override fun onError() {

    }
}